package com.jiantong.admin.controller.dongjiantong;

import com.jiantong.admin.controller.DjtBaseController;
import com.jiantong.admin.dto.Breed_Report_FormDto;
import com.jiantong.admin.dto.CityAreaDto;
import com.jiantong.admin.model.Common;
import com.jiantong.admin.model.PagingMz;
import com.jiantong.user.model.*;
import com.jiantong.user.service.*;
import com.jiantong.work.model.*;
import com.jiantong.work.service.*;
import io.terminus.boot.rpc.common.annotation.RpcConsumer;
import io.terminus.common.model.Paging;
import io.terminus.common.model.Response;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * Created by cao on 2017/7/25.
 */
@Controller
@RequestMapping("/djt/cert")
public class CertController extends DjtBaseController {
    private static final String BaseViews = VIEWS + "cert/";
    @RpcConsumer
    BreedReportReadService breedReportReadService;
    @RpcConsumer
    ButcherFactoryReadService butcherFactoryReadService;
    @RpcConsumer
    BreedFactoryReadService breedFactoryReadService;
    @RpcConsumer
    BreedReportSurveyRecordReadService breedReportSurveyRecordReadService;
    @RpcConsumer
    ButcherReportReadService butcherReportReadService;
    @RpcConsumer
    ButcherReportSurveyRecordReadService butcherReportSurveyRecordReadService;
    @RpcConsumer
    BreedReportsFormReadService breedReportsFormReadService;
    @RpcConsumer
    ButcherReportsFormReadService butcherReportsFormReadService;
    @RpcConsumer
    private UserReadService userReadService;
    @RpcConsumer
    private UserProfileReadService userProfileReadService;
    @RpcConsumer
    private GovernmentUserDutyReadService governmentUserDutyReadService;

   @RequestMapping ("animal_a_detail1")
    private String animal_a_detail1(){

        return BaseViews+"animal_a_detail1";
    }
    @RequestMapping ("animal_b_detail1")
    private String animal_b_detail1(){

        return BaseViews+"animal_b_detail1";
    }
    //动物开证统计
    @GetMapping("animalstat")
    private String animalstat(
            Model model, HttpServletRequest request, HttpServletResponse response) {

        Map mapuser = getarea(response, request);

        model.addAttribute("username", mapuser.get("username"));
        List<BreedReport> list = breedReportReadService.pagingCommon(0, 10000, new HashMap<>()).getResult().getData();
        Map map1 = new HashMap();
        List<CityAreaDto> areaList = new ArrayList<>();
        List<String> startList = new ArrayList<>();
        for (BreedReport report : list) {
            Map map = report.getReceiveAddressMap();
            if (map==null){
                map=new HashMap();
                map.put("city","");
                map.put("region","");
            }
            List<String> regionList = new ArrayList();
            if (areaList != null && areaList.size() > 0) {
                if (map != null && map.get("city") != null) {
                    for (CityAreaDto cityAreaDto : areaList) {
                        if (map.get("city").equals(cityAreaDto.getCity())) {
                            regionList = cityAreaDto.getRegions();
                            regionList.add((String) map.get("region"));
                            cityAreaDto.setRegions(regionList);
                        } else {
                            CityAreaDto cityAreaDto1 = new CityAreaDto();
                            cityAreaDto1.setCity(map.get("city").toString());
                            List arrList1 = new ArrayList();
                            arrList1.add(map.get("region").toString());
                            cityAreaDto1.setRegions(arrList1);
                        }
                    }

                }

            } else {
                CityAreaDto cityAreaDto = new CityAreaDto();
                cityAreaDto.setCity(map.get("city").toString());
                List arrlist = new ArrayList();
                arrlist.add(map.get("region"));
                cityAreaDto.setRegions(arrlist);
                areaList.add(cityAreaDto);
            }
            map1.put(report.getDeliverAddress(), 0);
        }
        Set mapkey = map1.keySet();
        Iterator mapIterator = mapkey.iterator();
        while (mapIterator.hasNext()) {
            startList.add(mapIterator.next().toString());
        }
        for (CityAreaDto cityAreaDto:areaList){
            List<String> listWithoutDup = new ArrayList<String>(new HashSet<String>(cityAreaDto.getRegions()));
            cityAreaDto.setRegions(listWithoutDup);
        }
        model.addAttribute("areaList", areaList);
        model.addAttribute("startList", startList);
        return BaseViews + "animalstat";
    }

    @GetMapping("animalsearch")
    @ResponseBody
    private PagingMz<List<CertResult>> animalsearch(@RequestParam(required = false) Integer page,
                                                    @RequestParam(required = false) Integer rows,
                                                    @RequestParam(required = false) Date start,
                                                    @RequestParam(required = false) Date end,
                                                    @RequestParam(required = false) String startarea,
                                                    @RequestParam(required = false) String endarea,
                                                    @RequestParam(required = false) Integer type,
                                                    @RequestParam(required = false) Integer cert,
                                                    @RequestParam(required = false) Integer count
    ) {
        Map criteria = new HashMap();
        if (page == null) {
            page = 0;
        }
        if (rows == null) {
            rows = 10;
        }
        if (start != null) {
            criteria.put("fromDate", start);
        }
        if (end != null) {
            criteria.put("toDate", end);
        }
        if (type != null && type != 0) {
            criteria.put("breedType", type);
        }
        if (startarea != null && !"全部".equals(startarea)) {
            criteria.put("deliverAddress", startarea);
        }

        if (cert != null && cert != 0) {
            criteria.put("isToLocal", cert);
        }
        if (count == null) {
            count = 1;
        }
        List mapList = new ArrayList<>();
        Map map = new HashMap();
        Paging<BreedReport> paging = (Paging<BreedReport>) breedReportReadService.cert(page, rows, criteria).getResult();
        Integer allanimal = 0;
        Integer allcert = 0;
        for (BreedReport report : paging.getData()) {
            if (count == 1) {
                if (map.containsKey(report.getDeliverAddress())) {
                    if (report.getQuantity() == null) {
                        report.setQuantity(0);
                    }
                    if (((CertResult) map.get(report.getDeliverAddress())).getAnimalnum()==null) {
                        ((CertResult) map.get(report.getDeliverAddress())).setAnimalnum(0);
                    }
                    map.put(report.getDeliverAddress(), new CertResult(((CertResult) map.get(report.getDeliverAddress())).getCertnum() + 1,
                            ((CertResult) map.get(report.getDeliverAddress())).getAnimalnum() + report.getQuantity(),
                            report.getDeliverAddress()));
                    if (report.getQuantity() != null) {
                        allanimal += report.getQuantity();
                        allcert += 1;
                    }
                } else {
                    map.put(report.getDeliverAddress(), new CertResult(1, report.getQuantity(), report.getDeliverAddress()));
                    if (report.getQuantity() != null) {
                        allanimal += report.getQuantity();

                        allcert += 1;
                    }
                }
            } else {
                if (map.containsKey(report.getReceiveAddressMap().get("region"))) {
                    map.put(report.getReceiveAddressMap().get("region"), new CertResult(((CertResult) map.get(report.getReceiveAddressMap().get("region"))).getCertnum() + 1,
                            ((CertResult) map.get(report.getReceiveAddressMap().get("region"))).getAnimalnum() + report.getQuantity(),
                            report.getReceiveAddressMap().get("region").toString()));
                    if (report.getQuantity() != null) {
                        allanimal += report.getQuantity();
                        allcert += 1;
                    }

                } else {
                    map.put(report.getReceiveAddressMap().get("region"), new CertResult(1, report.getQuantity(), report.getReceiveAddressMap().get("region").toString()));
                    if (report.getQuantity() != null) {
                        allanimal += report.getQuantity();
                        allcert += 1;
                    }
                }
            }
        }
        Set mapset = map.keySet();
        Iterator mapIterator = mapset.iterator();
        while (mapIterator.hasNext()) {
            CertResult certResult = (CertResult) map.get(mapIterator.next());
            certResult.setAllanimal(allanimal);
            certResult.setAllcert(allcert);
            if (certResult.getAnimalnum()!=null){
                mapList.add(certResult);
            }

        }
        CertResult certResult = new CertResult(-1, -1, "合计");
        certResult.setAllanimal(allanimal);
        certResult.setAllcert(allcert);
        mapList.add(certResult);
        Integer i = mapList.size();
        Long records = Long.parseLong(i.toString());
        Long pagetotal = (records - 1) / rows + 1;
        return new PagingMz<>(pagetotal, records, page, mapList);
    }

    //产品开证统计
    @GetMapping("productstat")
    private String productstat(Model model, HttpServletRequest request, HttpServletResponse response) {

        Map mapuser = getarea(response, request);

        model.addAttribute("username", mapuser.get("username"));
        List<ButcherReport> butcherReports = butcherReportReadService.pagingCommon(1, 1000, new HashMap()).getResult().getData();
        List<Long> butcherId = new ArrayList<>();
        Map areamap = new HashMap();
        for (ButcherReport report : butcherReports) {
            ButcherFactory butcherFactory = butcherFactoryReadService.findButcherFactoryById(report.getButcherFactoryId()).getResult();
            butcherFactory.getCity();
            butcherFactory.getRegion();
            if (areamap != null && areamap.containsKey(butcherFactory.getCity())) {
                List list = (List) areamap.get(butcherFactory.getCity());
                list.add(butcherFactory.getRegion());
                areamap.put(butcherFactory.getCity(), list);
            } else {
                List list = new ArrayList();
                list.add(butcherFactory.getRegion());
                areamap.put(butcherFactory.getCity(), list);
            }
        }
        Set mapKey = areamap.keySet();
        List<CityAreaDto> areaList = new ArrayList<>();
        Iterator iterator = mapKey.iterator();
        while (iterator.hasNext()) {
            String city = iterator.next().toString();
            List list = (List) areamap.get(city);
            CityAreaDto cityAreaDto = new CityAreaDto();
            cityAreaDto.setCity(city);
            cityAreaDto.setRegions(list);
            areaList.add(cityAreaDto);

        }
        model.addAttribute("areaList", areaList);
        return BaseViews + "productstat";
    }

    @GetMapping("productstatList")
    @ResponseBody
    private PagingMz<List> productstatList(@RequestParam(required = false) Integer page,
                                           @RequestParam(required = false) Integer rows,
                                           @RequestParam(required = false) Date start,
                                           @RequestParam(required = false) Date end,
                                           @RequestParam(required = false) String startarea,
                                           @RequestParam(required = false) Integer type,
                                           @RequestParam(required = false) Integer cert

    ) {
        Map criteria = new HashMap();


        if (page == null) {
            page = 0;
        }
        if (rows == null) {
            rows = 10;
        }
        if (start != null) {
            criteria.put("fromDate", start);
        }
        if (end != null) {
            criteria.put("toDate", end);
        }
        if (type != null && type != 0) {
            criteria.put("productType", type);
        }

        if (cert != null && cert != 0) {
            criteria.put("isLocal", cert);
        } else {
            criteria.put("isLocal", 1);
        }
        List mapList = new ArrayList<>();
        Map map = new HashMap();
        Paging<ButcherReport> paging = butcherReportReadService.pagingCert(page, rows, criteria).getResult();
        for (ButcherReport butcherReport : paging.getData()) {
            ButcherFactory butcherFactory = butcherFactoryReadService.findButcherFactoryById(butcherReport.getButcherFactoryId()).getResult();
            if (startarea != null && !"全部".equals(startarea)) {
                if (startarea.equals(butcherFactory.getRegion())) {
                    if (map.containsKey(butcherFactory.getRegion())) {
                        CertResult certResult = (CertResult) map.get(butcherFactory.getRegion());
                        certResult.setCertnum(certResult.getCertnum() + 1);
                        certResult.setAnimalnum(certResult.getAnimalnum() + butcherReport.getQuantity());
                        map.put(butcherFactory.getRegion(), certResult);
                    } else {
                        map.put(butcherFactory.getRegion(), new CertResult(1, butcherReport.getQuantity(), butcherFactory.getRegion()));
                    }

                }
            } else {
                if (map.containsKey(butcherFactory.getRegion())) {
                    CertResult certResult = (CertResult) map.get(butcherFactory.getRegion());
                    certResult.setCertnum(certResult.getCertnum() + 1);
                    certResult.setAnimalnum(certResult.getAnimalnum() + butcherReport.getQuantity());
                    map.put(butcherFactory.getRegion(), certResult);
                } else {
                    map.put(butcherFactory.getRegion(), new CertResult(1, butcherReport.getQuantity(), butcherFactory.getRegion()));
                }
            }
        }
        Set mapKey = map.keySet();
        Iterator mapIterator = mapKey.iterator();
        while (mapIterator.hasNext()) {
            String area = (String) mapIterator.next();
            CertResult certResult = (CertResult) map.get(area);
            certResult.setStartarea(area);
            mapList.add(certResult);
        }
        Integer i = mapList.size();
        Long records = Long.parseLong(i.toString());
        Long pagetotal = (records - 1) / rows + 1;
        return new PagingMz<>(pagetotal, records, page, mapList);
    }

    //动物A证
    @GetMapping("animala")
    private String animala(Model model, HttpServletRequest request, HttpServletResponse response) {
        Map mapuser = getarea(response, request);

        model.addAttribute("username", mapuser.get("username"));
        List<BreedReport> list = breedReportReadService.pagingCommon(0, 10000, new HashMap<>()).getResult().getData();
        Map map1 = new HashMap();
        List<CityAreaDto> areaList = new ArrayList<>();
        List<String> startList = new ArrayList<>();
        for (BreedReport report : list) {
            Map map = report.getReceiveAddressMap();
            if (map==null){
                map=new HashMap();
                map.put("city","");
                map.put("region","");
            }
            List<String> regionList = new ArrayList();
            if (areaList != null && areaList.size() > 0) {
                if (map != null && map.get("city") != null) {
                    for (CityAreaDto cityAreaDto : areaList) {
                        if (map.get("city").equals(cityAreaDto.getCity())) {
                            regionList = cityAreaDto.getRegions();
                            regionList.add((String) map.get("region"));
                            cityAreaDto.setRegions(regionList);
                        } else {
                            CityAreaDto cityAreaDto1 = new CityAreaDto();
                            cityAreaDto1.setCity(map.get("city").toString());
                            List arrList1 = new ArrayList();
                            arrList1.add(map.get("region").toString());
                            cityAreaDto1.setRegions(arrList1);
                        }
                    }

                }

            } else {
                CityAreaDto cityAreaDto = new CityAreaDto();
                cityAreaDto.setCity(map.get("city").toString());
                List arrlist = new ArrayList();
                arrlist.add(map.get("region"));
                cityAreaDto.setRegions(arrlist);
                areaList.add(cityAreaDto);
            }
            map1.put(report.getDeliverAddress(), 0);
        }
        Set mapkey = map1.keySet();
        Iterator mapIterator = mapkey.iterator();
        while (mapIterator.hasNext()) {
            startList.add(mapIterator.next().toString());
        }
        for (CityAreaDto cityAreaDto:areaList){
            List<String> listWithoutDup = new ArrayList<String>(new HashSet<String>(cityAreaDto.getRegions()));
            cityAreaDto.setRegions(listWithoutDup);
        }
        model.addAttribute("areaList", areaList);
        model.addAttribute("startList", startList);
        return BaseViews + "animala";
    }

    /* var time1 = $("#start").val();
        var time2 = $("#end").val();
        var area = $("#area").val();
        var startcity = $("#startcity").val();
        var endcity = $("#endcity").val();
        var zuofei = $("#zuofei").val();
        var name = $("#name").val();
        var own = $("#own").val();
        var num = $("#num").val()*/
    @GetMapping("animalalist")
    @ResponseBody
    private PagingMz<CertResult> animalaa(@RequestParam(required = false) Integer page,
                                          @RequestParam(required = false) Integer rows,
                                          @RequestParam(required = false) Date start,
                                          @RequestParam(required = false) Date end,
                                          @RequestParam(required = false) String startcity,
                                          @RequestParam(required = false) String endcity,
                                          @RequestParam(required = false) Integer zuofei,
                                          @RequestParam(required = false) String name,
                                          @RequestParam(required = false) String num,
                                          @RequestParam(required = false) String own,
                                          @RequestParam(required = false) String number,
                                          @RequestParam(required = false) Integer status
    ) {
        Map criteria = new HashMap();
        if (page == null) {
            page = 0;
        }
        if (rows == null) {
            rows = 10;
        }
        if (start != null) {
            criteria.put("fromDate", start);
        }
        if (end != null) {
            criteria.put("toDate", end);
        }
        if (startcity != null && !"全部".equals(startcity)) {
            criteria.put("deliverAddress", startcity);
        }
        if (zuofei != null && zuofei != 0) {
            criteria.put("deleteFlag", zuofei);
        }
        if(number!=null&&number.length()>0){
            criteria.put("number",number);
        }
        if (own != null && own.length() > 0) {
            criteria.put("owner", own);
        }
        if(status!=null&&status!=5){
            criteria.put("status", status);
        }
        criteria.put("isToLocal", -1);
        List<CertResult> resultList = new ArrayList<>();
        Paging<BreedReport> paging = (Paging<BreedReport>) breedReportReadService.cert(page, rows, criteria).getResult();
        List<BreedReport> reports = paging.getData();
        for(BreedReport report:reports){
            BreedReportSurveyRecord record = breedReportSurveyRecordReadService.findByReportId(report.getId()).getResult();
            String startarea = "";
            String name1="";
            if(record!=null){
                 startarea = record.getQuarantineCertNumber();
                 name1 = record.getVetUserName();
             }
             CertResult certResult = new CertResult(name1,report,startarea);
             if(num != null && num.length() > 0){
                if(record.getQuarantineCertNumber().contains(num)){
                    resultList.add(certResult);
                }

             }else{
                 resultList.add(certResult);
             }

        }


       Integer size = resultList.size();
        Long records = Long.parseLong(size.toString());
        Long pagetotal = (records - 1) / rows + 1;
        return new PagingMz<>(pagetotal, records, page, resultList);
    }


    //动物B证
    @GetMapping("animalb")
    private String animalb(Model model, HttpServletRequest request, HttpServletResponse response) {
        Map mapuser = getarea(response, request);

        model.addAttribute("username", mapuser.get("username"));
        List<BreedReport> list = breedReportReadService.pagingCommon(0, 10000, new HashMap<>()).getResult().getData();
        Map map1 = new HashMap();
        List<CityAreaDto> areaList = new ArrayList<>();
        List<String> startList = new ArrayList<>();
        for (BreedReport report : list) {
            Map map = report.getReceiveAddressMap();
            if (map==null){
                map=new HashMap();
                map.put("city","");
                map.put("region","");
            }
            List<String> regionList = new ArrayList();
            if (areaList != null && areaList.size() > 0) {
                if (map != null && map.get("city") != null) {
                    for (CityAreaDto cityAreaDto : areaList) {
                        if (map.get("city").equals(cityAreaDto.getCity())) {
                            regionList = cityAreaDto.getRegions();
                            regionList.add((String) map.get("region"));
                            cityAreaDto.setRegions(regionList);
                        } else {
                            CityAreaDto cityAreaDto1 = new CityAreaDto();
                            cityAreaDto1.setCity(map.get("city").toString());
                            List arrList1 = new ArrayList();
                            arrList1.add(map.get("region").toString());
                            cityAreaDto1.setRegions(arrList1);
                        }
                    }

                }

            } else {
                CityAreaDto cityAreaDto = new CityAreaDto();
                cityAreaDto.setCity(map.get("city").toString());
                List arrlist = new ArrayList();
                arrlist.add(map.get("region"));
                cityAreaDto.setRegions(arrlist);
                areaList.add(cityAreaDto);
            }
            map1.put(report.getDeliverAddress(), 0);
        }
        Set mapkey = map1.keySet();
        Iterator mapIterator = mapkey.iterator();
        while (mapIterator.hasNext()) {
            startList.add(mapIterator.next().toString());
        }
        for (CityAreaDto cityAreaDto:areaList){
            List<String> listWithoutDup = new ArrayList<String>(new HashSet<String>(cityAreaDto.getRegions()));
            cityAreaDto.setRegions(listWithoutDup);
        }
        model.addAttribute("areaList", areaList);
        model.addAttribute("startList", startList);
        return BaseViews + "animalb";
    }

    @GetMapping("animalblist")
    @ResponseBody
    private PagingMz<CertResult> animalab(@RequestParam(required = false) Integer page,
                                          @RequestParam(required = false) Integer rows,
                                          @RequestParam(required = false) Date start,
                                          @RequestParam(required = false) Date end,
                                          @RequestParam(required = false) String startcity,
                                          @RequestParam(required = false) String endcity,
                                          @RequestParam(required = false) Integer zuofei,
                                          @RequestParam(required = false) String name,
                                          @RequestParam(required = false) String num,
                                          @RequestParam(required = false) String own,
                                          @RequestParam(required = false) String number,
                                          @RequestParam(required = false) Integer status

    ) {
        Map criteria = new HashMap();
        if (page == null) {
            page = 0;
        }
        if (rows == null) {
            rows = 10;
        }
        if (start != null) {
            criteria.put("fromDate", start);
        }
        if (end != null) {
            criteria.put("toDate", end);
        }
        if (startcity != null && !"全部".equals(startcity)) {
            criteria.put("deliverAddress", startcity);
        }
        if (zuofei != null && zuofei != 0) {
            criteria.put("deleteFlag", zuofei);
        }
        if(number!=null&&number.length()>0){
            criteria.put("number",number);
        }
        if (own != null && own.length() > 0) {
            criteria.put("owner", own);
        }
        if(status!=null&&status!=5){
            criteria.put("status",status);
        }
        criteria.put("isToLocal", 1);
        List<CertResult> resultList = new ArrayList<>();
        Paging<BreedReport> paging = (Paging<BreedReport>) breedReportReadService.cert(page, rows, criteria).getResult();
        List<BreedReport> reports = paging.getData();
        for(BreedReport report:reports){
            BreedReportSurveyRecord record = breedReportSurveyRecordReadService.findByReportId(report.getId()).getResult();
            String startarea = "";
            String name1="";
            if(record!=null){
                startarea = record.getQuarantineCertNumber();
                name1 = record.getVetUserName();
            }
            CertResult certResult = new CertResult(name1,report,startarea);
            if(num != null && num.length() > 0){
                if(record.getQuarantineCertNumber().contains(num)){
                    resultList.add(certResult);
                }

            }else{
                resultList.add(certResult);
            }

        }


        Integer size = resultList.size();
        Long records = Long.parseLong(size.toString());
        Long pagetotal = (records - 1) / rows + 1;
        return new PagingMz<>(pagetotal, records, page, resultList);
    }


    //产品A证
    @GetMapping("producta")
    private String producta(Model model) {
        Common common = new Common(breedFactoryReadService, butcherFactoryReadService);
        List areaList = common.serachCityAreaDtoInBreefctory();
        model.addAttribute("areaList", areaList);
        return BaseViews + "producta";
    }

    @GetMapping("productalist")
    @ResponseBody
    private PagingMz<CertResult> productaList(@RequestParam(required = false) Integer page,
                                              @RequestParam(required = false) Integer rows,
                                              @RequestParam(required = false) Date start,
                                              @RequestParam(required = false) Date end,
                                              @RequestParam(required = false) String startcity,
                                              @RequestParam(required = false) Integer zuofei,
                                              @RequestParam(required = false) String name,
                                              @RequestParam(required = false) String num,
                                              @RequestParam(required = false) String own

    ) {
        Map criteria = new HashMap();
        if (page == null) {
            page = 0;
        }
        if (rows == null) {
            rows = 10;
        }
        if (num != null && num.length() > 0) {
            criteria.put("slaughterQuarantineCertNumber", num);
        }
        if (name != null && name.length() > 0) {
            criteria.put("surveyUserName", name);
        }
        List<ButcherReportSurveyRecord> butcherReportSurveyRecords = butcherReportSurveyRecordReadService.findByNameOrNumber(criteria).getResult();
        criteria.clear();
        List<ButcherFactory> butcherFactory = new ArrayList<>();
        if (startcity != null && !"全部".equals(startcity)) {
            butcherFactory = butcherFactoryReadService.findByRegion(startcity).getResult();
        }

        if (start != null) {
            criteria.put("fromDate", start);
        }
        if (end != null) {
            criteria.put("toDate", end);
        }

        if (zuofei != null) {
            criteria.put("deleteFlag", zuofei);
        }
        if (own != null && own.length() > 0) {
            criteria.put("owner", own);
        }
        criteria.put("isToLocal", 1);
        List<CertResult> resultList = new ArrayList<>();
        Paging<ButcherReport> paging = butcherReportReadService.pagingCert(page, rows, criteria).getResult();
        if (paging.getData().size() > 0) {
            if (butcherReportSurveyRecords != null && butcherReportSurveyRecords.size() > 0) {
                Iterator reportIterator = paging.getData().iterator();
                while (reportIterator.hasNext()) {
                    Boolean b = false;
                    ButcherReport report = (ButcherReport) reportIterator.next();
                    if (startcity != null && !"全部".equals(startcity)) {

                        for (ButcherFactory factory : butcherFactory) {
                            if (report.getButcherFactoryId() == factory.getId())
                                b = true;

                        }
                        if (b == false) {
                            reportIterator.remove();
                            b = false;
                            break;
                        }
                    }
                    for (ButcherReportSurveyRecord recoed : butcherReportSurveyRecords) {
                        if (recoed.getReportId() != report.getId()) {
                            reportIterator.remove();
                        } else {
                            ;
                            CertResult certResult = new CertResult(recoed.getSurveyUserName(), recoed.getSlaughterQuarantineCertNumber(), report);
                            certResult.setStartarea(butcherFactoryReadService.findButcherFactoryById(report.getButcherFactoryId()).getResult().getRegion());
                            resultList.add(certResult);
                        }
                    }
                    b = false;
                }
            }
        }
        Long records = paging.getTotal();
        Long pagetotal = (records - 1) / rows + 1;
        return new PagingMz<>(pagetotal, records, page, resultList);
    }


    //产品B证
    @GetMapping("productb")
    private String productb(Model model) {
        Common common = new Common(breedFactoryReadService, butcherFactoryReadService);
        List areaList = common.serachCityAreaDtoInBreefctory();
        model.addAttribute("areaList", areaList);
        return BaseViews + "productb";
    }

    @GetMapping("productblist")
    @ResponseBody
    private PagingMz<CertResult> productbList(@RequestParam(required = false) Integer page,
                                              @RequestParam(required = false) Integer rows,
                                              @RequestParam(required = false) Date start,
                                              @RequestParam(required = false) Date end,
                                              @RequestParam(required = false) String startcity,
                                              @RequestParam(required = false) Integer zuofei,
                                              @RequestParam(required = false) String name,
                                              @RequestParam(required = false) String num,
                                              @RequestParam(required = false) String own

    ) {
        Map criteria = new HashMap();
        if (page == null) {
            page = 0;
        }
        if (rows == null) {
            rows = 10;
        }
        if (num != null && num.length() > 0) {
            criteria.put("slaughterQuarantineCertNumber", num);
        }
        if (name != null && name.length() > 0) {
            criteria.put("surveyUserName", name);
        }
        List<ButcherReportSurveyRecord> butcherReportSurveyRecords = butcherReportSurveyRecordReadService.findByNameOrNumber(criteria).getResult();
        criteria.clear();
        List<ButcherFactory> butcherFactory = new ArrayList<>();
        if (startcity != null && !"全部".equals(startcity)) {
            butcherFactory = butcherFactoryReadService.findByRegion(startcity).getResult();
        }

        if (start != null) {
            criteria.put("fromDate", start);
        }
        if (end != null) {
            criteria.put("toDate", end);
        }

        if (zuofei != null) {
            criteria.put("deleteFlag", zuofei);
        }
        if (own != null && own.length() > 0) {
            criteria.put("owner", own);
        }
        criteria.put("isToLocal", -1);
        List<CertResult> resultList = new ArrayList<>();
        Paging<ButcherReport> paging = butcherReportReadService.pagingCert(page, rows, criteria).getResult();
        if (paging.getData().size() > 0) {
            if (butcherReportSurveyRecords != null && butcherReportSurveyRecords.size() > 0) {
                Iterator reportIterator = paging.getData().iterator();
                while (reportIterator.hasNext()) {
                    Boolean b = false;
                    ButcherReport report = (ButcherReport) reportIterator.next();
                    if (startcity != null && !"全部".equals(startcity)) {

                        for (ButcherFactory factory : butcherFactory) {
                            if (report.getButcherFactoryId() == factory.getId())
                                b = true;
                        }
                        if (b == false) {
                            reportIterator.remove();
                            b = false;
                            break;
                        }
                    }
                    for (ButcherReportSurveyRecord recoed : butcherReportSurveyRecords) {
                        if (recoed.getReportId() != report.getId()) {
                            reportIterator.remove();
                        } else {
                            CertResult certResult = new CertResult(recoed.getSurveyUserName(), recoed.getSlaughterQuarantineCertNumber(), report);
                            certResult.setStartarea(butcherFactoryReadService.findButcherFactoryById(report.getButcherFactoryId()).getResult().getRegion());
                            resultList.add(certResult);
                        }
                    }
                    b = false;
                }
            }
        }
        Long records = paging.getTotal();
        Long pagetotal = (records - 1) / rows + 1;
        return new PagingMz<>(pagetotal, records, page, resultList);
    }


    //动物A详细
    @GetMapping("animal_a_detail")
    private String animal_a_detail(@RequestParam Long id, Model model,HttpServletRequest request, HttpServletResponse response) {
        Map mapuser = getarea(response, request);

        model.addAttribute("username", mapuser.get("username"));
        BreedReport report = breedReportReadService.findById(Long.parseLong(id.toString())).getResult();
        BreedReportSurveyRecord record = breedReportSurveyRecordReadService.findByReportId(Long.parseLong(id.toString())).getResult();
        BreedReportsForm form = breedReportsFormReadService.findByReportId(Long.parseLong(id.toString())).getResult();
        if(record==null){
            record = new BreedReportSurveyRecord();
        }
        if(form==null){
            form = new BreedReportsForm();
        }
        Breed_Report_FormDto formDto = new Breed_Report_FormDto(report, form, record);
        Map map = report.getReceiveAddressMap();
        Set mapkey = map.keySet();
        Iterator mapIterator = mapkey.iterator();
        String address = "";
        String start = "";
        while (mapIterator.hasNext()) {
            address += map.get(mapIterator.next()) + " ";
        }
        BreedFactory breedFactory = breedFactoryReadService.findById(report.getBreedFactoryId()).getResult();
        start = breedFactory.getProvince() + " " + breedFactory.getCity() + " " + breedFactory.getRegion() + "" + report.getDeliverAddress();
        formDto.setReceiveAddress(address);
        formDto.setStartAddress(start);
        model.addAttribute("formDto", formDto);
        return BaseViews + "animal_a_detail";
    }

    @GetMapping("animalajax")
    @ResponseBody
    private Map animalajax(@RequestParam Long id) {

        BreedReport report = breedReportReadService.findById(Long.parseLong(id.toString())).getResult();
        BreedReportSurveyRecord record = breedReportSurveyRecordReadService.findByReportId(Long.parseLong(id.toString())).getResult();
        BreedReportsForm form = breedReportsFormReadService.findByReportId(Long.parseLong(id.toString())).getResult();
        Breed_Report_FormDto formDto = new Breed_Report_FormDto(report, form, record);
        Map map = report.getReceiveAddressMap();
        Set mapkey = map.keySet();
        Iterator mapIterator = mapkey.iterator();
        String address = "";
        while (mapIterator.hasNext()) {
            address += map.get(mapIterator.next());
        }
        Map map1 = new HashMap();
        map1.put("report", report);
        map1.put("record", record);
        map1.put("form", form);
        map1.put("address", address);
        return map1;
    }

    //动物B详细
    @GetMapping("animal_b_detail")
    private String animal_b_detail(@RequestParam Long id, Model model,HttpServletRequest request, HttpServletResponse response
    ) {
        Map mapuser = getarea(response, request);

        model.addAttribute("username", mapuser.get("username"));
        BreedReport report = breedReportReadService.findById(id).getResult();
        BreedReportSurveyRecord record = breedReportSurveyRecordReadService.findByReportId(id).getResult();
        BreedReportsForm form = breedReportsFormReadService.findByReportId(id).getResult();

        if(record==null){
            record = new BreedReportSurveyRecord();
        }
        if(form==null){
            form = new BreedReportsForm();
        }
        Breed_Report_FormDto formDto = new Breed_Report_FormDto(report, form, record);
        Map map = report.getReceiveAddressMap();
        Set mapkey = map.keySet();
        Iterator mapIterator = mapkey.iterator();
        String address = "";
        while (mapIterator.hasNext()) {
            address += map.get(mapIterator.next()) + " ";
        }
        String start = "";
        BreedFactory breedFactory = breedFactoryReadService.findById(report.getBreedFactoryId()).getResult();
        start = breedFactory.getProvince() + " " + breedFactory.getCity() + " " + breedFactory.getRegion() + "" + report.getDeliverAddress();
        formDto.setReceiveAddress(address);
        formDto.setStartAddress(start);
        model.addAttribute("formDto", formDto);
        return BaseViews + "animal_b_detail";
    }

    @GetMapping("animalbajax")
    @ResponseBody
    private Map animalbajax(@RequestParam Long id) {

        BreedReport report = breedReportReadService.findById(Long.parseLong(id.toString())).getResult();
        BreedReportSurveyRecord record = breedReportSurveyRecordReadService.findByReportId(Long.parseLong(id.toString())).getResult();
        BreedReportsForm form = breedReportsFormReadService.findByReportId(Long.parseLong(id.toString())).getResult();
        Breed_Report_FormDto formDto = new Breed_Report_FormDto(report, form, record);
        Map map = report.getReceiveAddressMap();
        Set mapkey = map.keySet();
        Iterator mapIterator = mapkey.iterator();
        String address = "";
        while (mapIterator.hasNext()) {
            address += map.get(mapIterator.next());
        }
        Map map1 = new HashMap();
        map1.put("report", report);
        map1.put("record", record);
        map1.put("form", form);
        map1.put("address", address);
        return map1;
    }

    //产品A详细
    @GetMapping("product_a_detail")
    private String product_a_detail(@RequestParam Long id, Model model) {
        ButcherReport report = butcherReportReadService.findById(id).getResult();
        ButcherReportsForm form = butcherReportsFormReadService.findByReportId(id).getResult();
        ButcherReportSurveyRecord record = butcherReportSurveyRecordReadService.findByReport(id).getResult();
        ButcherFactory butcherFactory = butcherFactoryReadService.findButcherFactoryById(report.getButcherFactoryId()).getResult();
        String address = butcherFactory.getCity() + butcherFactory.getRegion() + "";
        Map map = new HashMap();
        map.put("butcherReport", report);
        map.put("butcherReportsForm", form);
        map.put("butcherReportSurveyRecord", record);
        model.addAttribute("map", map);
        model.addAttribute("address", address);
        return BaseViews + "product_a_detail";
    }

    @GetMapping("productadetail")
    @ResponseBody
    private Map productadetail(@RequestParam Long id) {
        ButcherReport report = butcherReportReadService.findById(id).getResult();
        ButcherReportsForm form = butcherReportsFormReadService.findByReportId(id).getResult();
        ButcherReportSurveyRecord record = butcherReportSurveyRecordReadService.findByReport(id).getResult();
        Map map = new HashMap();
        map.put("butcherReport", report);
        map.put("butcherReportsForm", form);
        map.put("butcherReportSurveyRecord", record);

        return map;
    }

    //产品B详细
    @GetMapping("product_b_detail")
    private String product_b_detail(@RequestParam Long id, Model model) {
        ButcherReport report = butcherReportReadService.findById(id).getResult();
        ButcherReportsForm form = butcherReportsFormReadService.findByReportId(id).getResult();
        ButcherReportSurveyRecord record = butcherReportSurveyRecordReadService.findByReport(id).getResult();
        ButcherFactory butcherFactory = butcherFactoryReadService.findButcherFactoryById(report.getButcherFactoryId()).getResult();
        String address = butcherFactory.getCity() + butcherFactory.getRegion() + "";
        Map map = new HashMap();
        map.put("butcherReport", report);
        map.put("butcherReportsForm", form);
        map.put("butcherReportSurveyRecord", record);
        model.addAttribute("map", map);
        model.addAttribute("address", address);
        return BaseViews + "product_b_detail";
    }

    @GetMapping("productbdetail")
    @ResponseBody
    private Map productbdetail(@RequestParam Long id) {
        ButcherReport report = butcherReportReadService.findById(id).getResult();
        ButcherReportsForm form = butcherReportsFormReadService.findByReportId(id).getResult();
        ButcherReportSurveyRecord record = butcherReportSurveyRecordReadService.findByReport(id).getResult();
        Map map = new HashMap();
        map.put("butcherReport", report);
        map.put("butcherReportsForm", form);
        map.put("butcherReportSurveyRecord", record);

        return map;
    }


    public Map getarea(HttpServletResponse response, HttpServletRequest request) {
        List<String> list = new ArrayList<>();
        list.add("province");
        list.add("city");
        list.add("region");
        list.add("street");
        list.add("village");
        Cookie[] cookies = null;
        cookies = request.getCookies();
        String name = "";
        Map map = new HashMap();
        for (Cookie cookie : cookies) {

            if (cookie.getName().equals("djtid")) {
                String id = cookie.getValue();
                int Id = Integer.parseInt(id);
                Response<User> userResponse = userReadService.findById(Integer.toUnsignedLong(Id));
                name = userResponse.getResult().getName();
                map.put("username", name);
                switch (userResponse.getResult().getAreaLevel()) {
                    case 1:
                        UserProfile userProfile = userProfileReadService.findUserProfileById(userResponse.getResult().getId()).getResult();
                        String Province = userProfile.getProvince();
                        Map map6 = new HashMap();
                        map6.put("province", Province);
                        List<BreedFactory> breedFactoryList = (List<BreedFactory>) breedFactoryReadService.findByArea(map6).getResult();
                        //获取所有省下城市

                        Map map1 = new HashMap();
                        map1.put("area1", list.get(1));
                        map1.put("area2", list.get(0));
                        map1.put("area3", Province);
                        List<String> citys = breedFactoryReadService.serachAllregion1(map1);
                        //获取城市下所有区
                        List<CityAreaDto> cityAreaDtoList = new ArrayList<>();
                        for (String city : citys) {
                            CityAreaDto cityAreaDto = new CityAreaDto();
                            Map map2 = new HashMap();
                            map2.put("area1", list.get(2));
                            map2.put("area2", list.get(1));
                            map2.put("area3", city);
                            List<String> regions = breedFactoryReadService.serachAllregion1(map2);
                            cityAreaDto.setCity(city);
                            cityAreaDto.setRegions(regions);
                            cityAreaDtoList.add(cityAreaDto);

                        }
                        map.put("cityAreaDtoList", cityAreaDtoList);
                        map.put("breedFactorys", breedFactoryList);
                        //switch break;
                        break;
                    case 2:
                        UserProfile userProfile2 = userProfileReadService.findUserProfileById(userResponse.getResult().getId()).getResult();
                        String city1 = userProfile2.getCity();
                        Map map7 = new HashMap();
                        map7.put("city", city1);
                        List<BreedFactory> breedFactoryList1 = (List<BreedFactory>) breedFactoryReadService.findByArea(map7).getResult();
                        //获取所有省下城市

                        Map map21 = new HashMap();
                        map21.put("area1", list.get(2));
                        map21.put("area2", list.get(1));
                        map21.put("area3", city1);
                        List<String> citys2 = breedFactoryReadService.serachAllregion1(map21);
                        //获取城市下所有区
                        List<CityAreaDto> cityAreaDtoList1 = new ArrayList<>();
                        for (String city : citys2) {
                            CityAreaDto cityAreaDto = new CityAreaDto();
                            Map map2 = new HashMap();
                            map2.put("area1", list.get(3));
                            map2.put("area2", list.get(2));
                            map2.put("area3", city);
                            List<String> regions = breedFactoryReadService.serachAllregion1(map2);
                            cityAreaDto.setCity(city);
                            cityAreaDto.setRegions(regions);
                            cityAreaDtoList1.add(cityAreaDto);

                        }
                        map.put("cityAreaDtoList", cityAreaDtoList1);
                        map.put("breedFactorys", breedFactoryList1);
                        //switch break;
                        break;
                    case 3://区
                        UserProfile userProfile3 = userProfileReadService.findUserProfileById(userResponse.getResult().getId()).getResult();
                        String region = userProfile3.getRegion();
                        Map map36 = new HashMap();
                        map36.put("region", region);
                        List<BreedFactory> breedFactoryList3 = (List<BreedFactory>) breedFactoryReadService.findByArea(map36).getResult();
                        //获取所有区下城市镇

                        Map map31 = new HashMap();
                        map31.put("area1", list.get(3));
                        map31.put("area2", list.get(2));
                        map31.put("area3", region);
                        List<String> citys3 = breedFactoryReadService.serachAllregion1(map31);
                        //获取对应镇 对应村
                        List<CityAreaDto> cityAreaDtoList3 = new ArrayList<>();
                        for (String city : citys3) {
                            CityAreaDto cityAreaDto = new CityAreaDto();
                            Map map2 = new HashMap();
                            map2.put("area1", list.get(4));
                            map2.put("area2", list.get(3));
                            map2.put("area3", city);
                            List<String> regions = breedFactoryReadService.serachAllregion1(map2);
                            cityAreaDto.setCity(city);
                            cityAreaDto.setRegions(regions);
                            cityAreaDtoList3.add(cityAreaDto);

                        }
                        map.put("cityAreaDtoList", cityAreaDtoList3);
                        map.put("breedFactorys", breedFactoryList3);
                        //switch break;
                        break;
                    case 4://镇
                        UserProfile userProfile4 = userProfileReadService.findUserProfileById(userResponse.getResult().getId()).getResult();
                        String street = userProfile4.getStreet();
                        Map map46 = new HashMap();
                        map46.put("street", street);
                        List<BreedFactory> breedFactoryList4 = (List<BreedFactory>) breedFactoryReadService.findByArea(map46).getResult();
                        //获取所有镇下所有村

                        Map map41 = new HashMap();
                        map41.put("area1", list.get(4));
                        map41.put("area2", list.get(3));
                        map41.put("area3", street);
                        List<String> citys4 = breedFactoryReadService.serachAllregion1(map41);//所有村

                        List<CityAreaDto> cityAreaDtoList4 = new ArrayList<>();

                        CityAreaDto cityAreaDto = new CityAreaDto();

                        cityAreaDto.setCity(street);
                        cityAreaDto.setRegions(citys4);
                        cityAreaDtoList4.add(cityAreaDto);


                        map.put("cityAreaDtoList", cityAreaDtoList4);
                        map.put("breedFactorys", breedFactoryList4);
                        //switch break;
                        break;
                    case 5://村
                        List<GovernmentUserDuty> governmentUserDutyList= governmentUserDutyReadService.findGovernmentUserDutiesByUserId(userResponse.getResult().getId(),null).getResult();
                        List<Long> longlist=new ArrayList<>();
                        for (GovernmentUserDuty governmentUserDuty:governmentUserDutyList){
                            longlist.add(governmentUserDuty.getFactoryOrPointId());
                        }
                        List<String> villages=new ArrayList<>();
                        List<BreedFactory> breedFactoryList2= breedFactoryReadService.findBreedFactoryDtoByIds(longlist).getResult();
                        for (BreedFactory breedFactory:breedFactoryList2){
                            villages.add(breedFactory.getVillage());  ;
                        }

                        List<String> listWithoutDup = new ArrayList<String>(new HashSet<String>(villages));


                        List<CityAreaDto> cityAreaDtoList5=new ArrayList<>();

                        CityAreaDto cityAreaDto1 = new CityAreaDto();
                        cityAreaDto1.setCity(" ");

                        // cityAreaDto1.setCity(village);
                        cityAreaDto1.setRegions(listWithoutDup);

                        cityAreaDtoList5.add(cityAreaDto1);


                        map.put("cityAreaDtoList",cityAreaDtoList5);
                        map.put("breedFactorys",breedFactoryList2);
                        //switch break;
                        break;
                }


                break;
            }

        }

        return map;
    }


    public List findFactoryIdByArea(String region, int breedType) {

        Map map = new HashMap();
        if (breedType == -1) {
            map.put("breedType", null);
        } else {
            map.put("breedType", breedType);
        }
        List<String> list1 = new ArrayList<>();
        String[] list = region.split(",");

        for (int i = 0; i < list.length; i++) {
            list1.add(list[i]);
        }
        map.put("areas", list1);

        List<BreedFactory> breedFactoryList = (List<BreedFactory>) breedFactoryReadService.findByArea(map).getResult();

        return breedFactoryList;
    }


}

class CertResult {

    private Integer certnum;//申报数
    private Integer animalnum;//产品数
    private String name;//开证人
    private BreedReport breedReport;
    private String num;//编号
    private ButcherReport butcherReport;
    private String startarea;//
    private Integer allcert;
    private Integer allanimal;

    public void setAllcert(Integer allcert) {
        this.allcert = allcert;
    }

    public void setAllanimal(Integer allanimal) {
        this.allanimal = allanimal;
    }

    public Integer getAllcert() {
        return allcert;
    }

    public Integer getAllanimal() {
        return allanimal;
    }

    public CertResult(String name, String num, ButcherReport butcherReport) {
        this.name = name;
        this.num = num;
        this.butcherReport = butcherReport;
    }

    public CertResult(String name, BreedReport breedReport, String num) {
        this.name = name;
        this.breedReport = breedReport;
        this.num = num;
    }

    public void setStartarea(String startarea) {
        this.startarea = startarea;
    }

    public String getStartarea() {
        return startarea;
    }

    public void setButcherReport(ButcherReport butcherReport) {
        this.butcherReport = butcherReport;
    }

    public ButcherReport getButcherReport() {
        return butcherReport;
    }

    public void setBreedReport(BreedReport breedReport) {
        this.breedReport = breedReport;
    }

    public void setNum(String num) {
        this.num = num;
    }

    public BreedReport getBreedReport() {
        return breedReport;
    }

    public String getNum() {
        return num;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getCertnum() {
        return certnum;
    }

    public Integer getAnimalnum() {
        return animalnum;
    }

    public void setCertnum(Integer certnum) {
        this.certnum = certnum;
    }

    public void setAnimalnum(Integer animalnum) {
        this.animalnum = animalnum;
    }

    public CertResult(Integer certnum, Integer animalnum, String name) {
        this.certnum = certnum;
        this.animalnum = animalnum;
        this.name = name;
    }
}
